package com.linq.cool.pay.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.linq.cool.common.core.utils.JsonUtils;
import com.linq.cool.common.core.utils.StringUtils;
import com.linq.cool.pay.domain.AlipayConfig;
import com.linq.cool.pay.enums.AlipayTradeStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: yqlin
 * @Date: 2021/1/20 22:50
 * @Description: 支付接口
 * @Version: 1.0.0
 */
@Slf4j
@RestController
@RequestMapping
public class PayController {
    /**
     * 支付宝回调
     *
     * @param orderId 订单号
     * @param request
     */
    @PostMapping("alipay/callback/{orderId}")
    public void aliPayCallback(@PathVariable("orderId") String orderId, HttpServletRequest request) {
        Map<String, String> parameterMap = this.getParameterMap(request);
        log.info("支付宝支付回调参数: {}", parameterMap);
        // 交易状态
        String tradeStatus = parameterMap.get("trade_status");
        if (AlipayTradeStatus.TRADE_SUCCESS.name().equals(tradeStatus)) {
            try {
                //验证是否为支付宝发来的信息
                boolean singVerified = AlipaySignature.rsaCheckV1(parameterMap, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
                log.info("验证签名结果：{}", singVerified);
                String refundFee = parameterMap.get("refund_fee");
                if (StringUtils.isNotBlank(refundFee)) {
                    //说明是退费
                    log.info("退费成功：退费的子订单ID为：{}", parameterMap.get("out_biz_no"));
                    //更新订单状态
                } else {
                    //说明支付
                    log.info("收费成功，平台ID: {}", parameterMap.get("trade_no"));
                }
                log.info(JsonUtils.toJson(parameterMap));
            } catch (AlipayApiException ex) {
                log.error("订单号:[ {} ]验证签名出现异常 :{}", orderId, ex.getMessage());
            }
        }
        if (AlipayTradeStatus.WAIT_BUYER_PAY.name().equals(tradeStatus)) {
            log.info("订单号: {} ,二维码已扫描，等待支付", orderId);
        }
    }


    /**
     * 获取request中的参数集合转Map
     * Map<String,String> parameterMap = RequestUtil.getParameterMap(request)
     *
     * @param request
     *
     * @return
     */
    public Map<String, String> getParameterMap(HttpServletRequest request) {
        Map<String, String> map = new HashMap<>(2);
        Enumeration<String> paramNames = request.getParameterNames();
        while (paramNames.hasMoreElements()) {
            String paramName = paramNames.nextElement();
            String[] paramValues = request.getParameterValues(paramName);
            if (paramValues.length == 1) {
                String paramValue = paramValues[0];
                if (paramValue.length() != 0) {
                    map.put(paramName, paramValue);
                }
            }
        }
        return map;
    }
}
